<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import vkDataGoodsSkuPopupCenter from '@/components/vk-data-goods-sku-popup-center.vue'
import vkDataInputNumberBox from '@/components/vk-data-input-number-box.vue'
import { getGoodsByIdAPI, getCollectStatusAPI, editStatusAPI } from '@/services/goods'
import type { GoodsResult } from '@/types/goods'
import { useCart, useOrder, useMemberStore, useStore } from '@/stores'
import type { IcartItem } from '@/types/cart'
import { formatChineseJson, getOrCreateUUID } from '@/utils/http'
const { addCartData, getByIdNum, getCartTotalNum } = useCart()
const { addOrderData, getOrderData } = useOrder()
const { getUserInfo, setCollectCount } = useMemberStore()
const { getStoreInfo } = useStore()
const cartMode = ref(1)
const hasSpec = ref(false)

const cartNumTotal = ref(0)

// uni-ui 弹出层组件 ref
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const currentIndex = ref(0)

const isCollect = ref(0 as number)

// 接收页面参数
const query = defineProps<{
  id: string
}>()

// 商品信息
const goodsInfo = ref({} as GoodsResult)
const priceRange = computed(() => {
  return (
    '￥' +
    (goodsInfo.value.heightPrice
      ? goodsInfo.value.price + '~' + goodsInfo.value.heightPrice
      : goodsInfo.value.price)
  )
})

onShow(async () => {
  getGoodsByIdAPI(query.id).then((res) => {
    goodsInfo.value = { ...res.data, num: 1 }
  })
  const collectRes = await getCollectStatusAPI({
    goodsId: query.id,
    isSetmeal: 0,
    userId: getUserInfo().id,
  })
  isCollect.value = collectRes.data as number
})

const onChange: UniHelper.SwiperOnChange = (ev) => {
  currentIndex.value = ev.detail.current
}

// 点击图片时
const onTapImage = (url: string) => {
  // 大图预览
  uni.previewImage({
    current: url,
    urls: goodsInfo.value.image_list!.map((item: any) => item.url),
  })
}

// 弹出层条件渲染
const popupName = ref<'address' | 'service'>()
const openPopup = (name: typeof popupName.value) => {
  // 修改弹出层名称
  popupName.value = name
  // 打开弹出层
  popup.value?.open()
}

const navMember = () => {
  uni.navigateTo({
    url: '/pages/login/login',
  })
}

// 是否显示SKU组件
const isShowSku = ref(false)

const onCart = () => {
  if (!goodsInfo.value.hasSku) {
    cartNumTotal.value = goodsInfo.value['num']
    const skuId: number = goodsInfo.value['sku_list'][0]['_id']

    // 加入购物车
    const cartRecord: IcartItem = {
      checked: true,
      id: goodsInfo.value._id,
      storeId: getStoreInfo()?.storeId,
      goods_id: goodsInfo.value._id,
      skuId,
      specification: '',
      name: goodsInfo.value.name,
      image: goodsInfo.value.imageUrl,
      description: goodsInfo.value.description,
      price: goodsInfo.value.price,
      costPrice: 0,
      num: cartNumTotal.value,
      isSetmeal: 0,
      setmealPid: null,
      hasSku: 0,
    }
    console.log(cartRecord)
    addCartData(cartRecord, false)
  } else {
    onOpenSkuPopup(2)
  }
}

const onOpenSkuPopup = (tag: number) => {
  cartMode.value = tag
  isShowSku.value = true
  // uni.navigateTo({ url: '/pagesOrder/create/create' })
}
const onCloseSkuPopup = (val: any) => {}

const specInfo = ref('请选择')

const addCart = async (ev: any) => {
  goodsInfo.value['num'] = ev.buy_num
  cartNumTotal.value = goodsInfo.value['num']
  isShowSku.value = false
  specInfo.value = formatChineseJson(ev.specification)
  if (goodsInfo.value.hasSku) {
    const cartRecord: IcartItem = {
      checked: true,
      id: ev._id,
      storeId: getStoreInfo()?.storeId,
      goods_id: goodsInfo.value._id,
      hasSku: 1,
      name: ev.goods_name,
      image: ev.image,
      description: goodsInfo.value.description,
      specification: ev.specification,
      price: ev.price,
      costPrice: ev.cost,
      num: cartNumTotal.value,
      isSetmeal: 0,
      setmealPid: null,
      skuId: ev._id,
    }

    console.log(cartRecord)
    addCartData(cartRecord, false)
  }
}
const buyNow = (ev: any) => {
  console.log(ev) // _id, goods_id
  isShowSku.value = false

  specInfo.value = formatChineseJson(ev.specification)
  const orderRecord: IcartItem = {
    checked: true,
    id: ev._id,
    storeId: getStoreInfo()?.storeId,
    goods_id: ev.goods_id,
    hasSku: 1,
    name: ev.goods_name,
    image: ev.image,
    description: goodsInfo.value.description,
    specification: ev.specification,
    price: ev.price,
    costPrice: ev.cost,
    num: ev.buy_num,
    isSetmeal: 0,
    setmealPid: null,
    skuId: ev._id,
  }

  addOrderData([orderRecord])
  uni.navigateTo({ url: '/pagesOrder/create/create' })
}
const numChange = (item: any) => {
  console.log(item)
  goodsInfo.value['num'] = item.value
}

const onBuy = () => {
  if (goodsInfo.value.hasSku) {
    onOpenSkuPopup(3)
  } else {
    const skuId: number = goodsInfo.value['sku_list'][0]['_id']
    const orderRecord: IcartItem = {
      checked: true,
      id: goodsInfo.value._id,
      storeId: getStoreInfo()?.storeId,
      goods_id: goodsInfo.value._id,
      hasSku: 0,
      name: goodsInfo.value.name,
      image: goodsInfo.value.imageUrl,
      description: goodsInfo.value.description,
      specification: '',
      price: goodsInfo.value.price,
      costPrice: 0,
      num: goodsInfo.value['num'],
      isSetmeal: 0,
      setmealPid: null,
      skuId,
    }
    addOrderData([orderRecord])
    uni.navigateTo({ url: '/pagesOrder/create/create' })
  }
}

const goToCart = () => {
  uni.switchTab({
    url: '/pages/cart/cart',
  })
}

const editStatuhandle = async () => {
  const isCollectValue = isCollect.value === 1 ? 0 : 1
  await editStatusAPI({
    goodsId: query.id,
    isSetmeal: 0,
    userId: getUserInfo().id,
    collectStatus: isCollectValue,
  })

  isCollect.value = isCollectValue
  setCollectCount(1, isCollectValue === 1)
}
</script>

<template>
  <view class="good-container">
    <scroll-view scroll-y class="viewport">
      <!-- 基本信息 -->
      <view class="goods">
        <!-- 商品主图 -->
        <view class="preview">
          <swiper @change="onChange" circular>
            <swiper-item
              @tap="onTapImage(item.url)"
              v-for="item in goodsInfo.image_list"
              :key="item.imageId"
            >
              <image mode="aspectFill" :src="item.url" />
            </swiper-item>
          </swiper>
          <view class="indicator">
            <text class="current">{{ currentIndex + 1 }}</text>
            <text class="split">/</text>
            <text class="total">{{ goodsInfo.image_list?.length || 0 }}</text>
          </view>

          <view class="heart" @click="editStatuhandle">
            <text class="icon-heart" :class="{ active: isCollect === 1 }"></text>
          </view>
        </view>

        <!-- 商品名称+价格 -->
        <view class="meta">
          <view class="name ellipsis">{{ goodsInfo.name }}</view>
          <view class="info ellipsis">
            <rich-text :nodes="goodsInfo.description"></rich-text>
          </view>
          <view class="price">
            <text class="symbol">{{ priceRange }}</text>
            <!-- <text class="acount">{{ 234.8 }}</text> -->
          </view>
        </view>

        <view class="info-detail">
          <view class="title">营养信息</view>
          <!-- 商品详解：做工，配方 -->
          <view class="desc">
            <rich-text :nodes="goodsInfo.facts"></rich-text>
          </view>
        </view>

        <view class="spec" v-if="goodsInfo.hasSku" @click="onOpenSkuPopup(1)">
          <view class="left">
            <view class="spec-name">规格</view>
            <view class="spec-info">
              {{ specInfo }}
              <!-- <template :key="index" v-for="(item, index) in goodsInfo.spec_list">
                <view>
                  <text>{{ item.name }}: </text>
                  <text :key="idx" v-for="(sitem, idx) in item.list"> {{ sitem.name }} </text>
                </view>
              </template> -->
            </view>
          </view>
          <view class="right">
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="opeate-number" v-else>
          <view class="left">
            <text class="name">数量</text>
          </view>
          <view class="right">
            <vk-data-input-number-box
              v-model="goodsInfo['num']"
              :min="0"
              :max="50"
              :step="1"
              :step-strictly="true"
              :disabled="false"
              :disabled-input="false"
              :cursor-spacing="100"
              :long-press="true"
              :press-time="250"
              :positive-integer="true"
              @change="numChange"
            ></vk-data-input-number-box>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 模式 1:都显示  2:只显示购物车 3:只显示立即购买 4:显示缺货按钮 默认 1     v-model="isShowSku" -->
    <vk-data-goods-sku-popup-center
      ref="skuPopup"
      v-model="isShowSku"
      border-radius="20"
      :z-index="990"
      :localdata="goodsInfo"
      :mode="cartMode"
      :amount-type="0"
      :stepBuyNum="1"
      :minBuyNum="1"
      theme="black-white"
      @close="onCloseSkuPopup"
      @add-cart="addCart"
      @buy-now="buyNow"
    ></vk-data-goods-sku-popup-center>

    <!-- 用户操作 -->
    <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <view class="icons-button" @click="goToCart">
        <text class="iconfont icon-cart-add"></text>
        <text class="tag" v-if="getCartTotalNum()">{{ getCartTotalNum() }}</text>
      </view>
      <view class="addcart" @tap="onCart()"> 加入购物车 </view>
      <view class="buynow" @tap="onBuy()"> 立即购买 </view>
    </view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.good-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.viewport {
  background-color: #f9fafb;
  flex: 1;
  padding-bottom: 50rpx;

  .goods {
    .preview {
      height: 686rpx;
      position: relative;
      .image {
        width: 750rpx;
        height: 750rpx;
      }
      .indicator {
        box-sizing: border-box;
        padding: 0 24rpx;
        line-height: 56rpx;
        border-radius: 28rpx;
        color: #fff;
        font-size: $font-size;
        font-weight: $font-regular-weight;
        background-color: rgba(0, 0, 0, 0.4);
        position: absolute;
        bottom: 30rpx;
        right: 30rpx;
      }
      .heart {
        box-sizing: border-box;
        // padding: 0 24rpx;
        position: absolute;
        top: 30rpx;
        right: 30rpx;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.8);
        width: 46rpx;
        height: 46rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .icon-heart {
          &::before {
            content: '\e708';
            font-family: 'iconfont' !important;
            color: #ccc;
            font-size: 40rpx;
          }
        }
        .icon-heart {
          &.active {
            &::before {
              color: $price-font-color;
              content: '\e708';
              font-family: 'iconfont' !important;
              font-size: 40rpx;
            }
          }
        }
      }
    }
    .meta {
      padding: $lager-padding;
      border-radius: $border-lager-radius;
      display: flex;
      flex-direction: column;
      background-color: #fff;

      margin: $medium-padding 0;
      // align-items: center;
      // justify-content: space-between;
      .name {
        color: $good-font-title-color;
        font-size: $font-largex-size;
        font-weight: $font-bold-weight;
      }
      .info {
        color: $font-color;
        font-size: $font-size;
        margin-top: 12rpx;
        margin-bottom: 12rpx;
      }
      .price {
        .symbol {
          font-size: $font-largexx-size;
          color: $price-font-color;
          font-weight: $font-bold-weight;
        }
        .acount {
          margin-left: $smallx-padding;
          font-size: $font-size;
          color: $good-font-con-color;
          font-weight: $font-weight;
          text-decoration: line-through;
        }
      }
    }
    .info-detail {
      padding: $lager-padding;
      border-radius: $border-lager-radius;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      margin: $medium-padding 0;
      .title {
        color: $good-font-title-color;
        font-size: $font-largex-size;
        font-weight: $font-bold-weight;
      }

      .desc {
        margin: 12rpx 0;
        color: $font-color;
        font-size: $font-size;
        font-weight: $font-regular-weight;
        line-height: 1.5;
        text-align: justify;
      }
    }
    .instructions {
      margin: 30rpx 0;
      padding: 0 60rpx;
      color: #909090;
      font-size: 28rpx;
      line-height: 1.5;
      text-align: justify;
    }

    .spec {
      padding: $lager-padding;
      border-radius: $border-lager-radius;
      display: flex;
      flex-direction: row;
      background-color: #fff;
      margin: $medium-padding 0;
      justify-content: space-between;
      align-items: center;
      .left {
        display: flex;
        flex-direction: row;
        .spec-name {
          color: $font-color;
          font-size: $font-medium-size;
          font-weight: $font-regular-weight;
          line-height: 1.5;
          margin-right: 10rpx;
        }
        .spec-info {
          color: $good-font-con-color;
          font-size: $font-size;
          font-weight: $font-regular-weight;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-start;
        }
      }
      .right {
        color: $color;
        font-size: $font-largex-size;
        font-weight: $font-bold-weight;
      }
    }

    .opeate-number {
      padding: $lager-padding;
      border-radius: $border-lager-radius;
      display: flex;
      flex-direction: row;
      background-color: #fff;
      margin: $medium-padding 0;
      justify-content: space-between;
      align-items: center;
      .left {
        .name {
          color: $font-color;
          font-size: $font-medium-size;
          font-weight: $font-regular-weight;
        }
      }
      .right {
      }
    }
  }

  /* 商品详情 */
  .detail {
    padding-left: 20rpx;
    .content {
      margin-left: -20rpx;
      .image {
        width: 100%;
      }
    }
    .properties {
      padding: 0 20rpx;
      margin-bottom: 30rpx;
      .item {
        display: flex;
        line-height: 2;
        padding: 10rpx;
        font-size: 26rpx;
        color: #333;
        border-bottom: 1rpx dashed #ccc;
      }
      .label {
        width: 200rpx;
      }
      .value {
        flex: 1;
      }
    }
  }
}

/* 底部工具栏 */
.toolbar {
  background-color: #fff;
  height: 138rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid $border-color;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  flex-direction: row;

  .buynow,
  .addcart {
    width: 290rpx;
    height: 88rpx;

    background-color: $color;
    color: #fff;
    font-size: $font-medium-size;
    font-weight: $font-medium-weight;
    border-radius: 44rpx;
    // margin-left: 20rpx;

    line-height: 88rpx;
    text-align: center;
  }
  .buynow {
    background-color: $red-color;
    margin-left: 20rpx;
  }
  .icons-button {
    margin-right: 40rpx;
    margin-left: 10rpx;
    position: relative;
    .iconfont {
      font-size: 60rpx;
      color: $font-color;
    }
    .tag {
      position: absolute;
      right: -23rpx;
      top: -24rpx;
      max-width: 60rpx;
      max-height: 30rpx;
      min-width: 30rpx;
      min-height: 30rpx;
      background-color: #fa5151;
      padding: 8rpx;
      border-radius: 50%;
      color: #fff;
      text-align: center;
      line-height: 30rpx;
      border: 1px solid #fff4ed;
      font-size: $font-small-size;
    }
    .icon-cart {
      display: block;
      font-size: 60rpx;
      color: $font-color;
    }
  }
}
</style>
